package ruc.TDEngine.write;

import okhttp3.Response;
import ruc.Consts.constant;
import ruc.utils.IOUtils;
import ruc.TDEngine.TDEngine_Common;

public class TDEngine_DifferentRecordWrite {
    private String IP, port, dbName, tbName, userName, password;

    public TDEngine_DifferentRecordWrite(String IP, String port, String dbName, String tbName, String userName, String password) {
        this.IP = IP;
        this.port = port;
        this.dbName = dbName;
        this.tbName = tbName;
        this.userName = userName;
        this.password = password;
    }

    private long send(String sql) {
        long st_time = System.nanoTime();
        Response response = TDEngine_Common.send(TDEngine_Common.getRequest(sql, userName, password, IP, port));
        assert response != null;
        response.close();
        return (System.nanoTime() - st_time) / constant.Ns2Ms;
    }

    private void DifferentRecordLengthInsert(int[] recordLength, String[] val) {
        for (int value : recordLength) {
            TDEngine_Common.dropAndCreate(constant.IP, constant.TDEngine_port, constant.dbName, constant.DifferentRecordWrite_tbName, constant.userName, constant.passWord);

            long costTime = 0;
            StringBuilder sql = new StringBuilder(String.format("insert into %s.%s values", dbName, tbName));
            int cnt = 0;
            for (String s : val) {
                String[] t = s.split(":");
                String tmp = String.format(" (%s,\"%s\",\"%s\",\"%s\",%s, %s, %s)", t[0], t[1], t[2], t[3], t[4], t[5], t[6]);

                sql.append(tmp);
                cnt++;
                if (sql.toString().getBytes().length > value || cnt > constant.threshold) {
                    costTime += send(sql.toString());
                    sql = new StringBuilder(String.format("insert into %s.%s values", dbName, tbName));
                    cnt = 0;
                }
            }

            if (cnt > 0) {
                costTime += send(sql.toString());
            }

            System.out.printf("[TSBenchD] [TDEngine_DifferentRecordWrite] >>>>> Record Length %d Byte, Number of lines: %d 行， costTime: %d ms >>>>> \n", value, val.length, costTime);
            IOUtils.WriteData(constant.GetWriteFilePath("TDEngine", "DifferentRecordWrite"),
                    new String[]{ String.valueOf(value), String.valueOf(val.length), String.valueOf(costTime)});
        }
    }

    public static void main(String[] args) {
        TDEngine_DifferentRecordWrite  root = new TDEngine_DifferentRecordWrite (constant.IP, constant.TDEngine_port, constant.dbName, constant.DifferentRecordWrite_tbName, constant.userName, constant.passWord);
        root.DifferentRecordLengthInsert(constant.DiffRecordLength, IOUtils.GetData());
    }
}
